<template>
  <div class="shop-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="积分商城" name="shop">
        <el-card class="points-card">
          <template #header>
            <div class="card-header">
              <span>我的积分</span>
            </div>
          </template>
          <div class="points-content">
            <div class="points-number">{{ userPoints }}</div>
            <div class="points-label">可用积分</div>
          </div>
        </el-card>

        <el-card class="products-card">
          <template #header>
            <div class="card-header">
              <span>积分商城</span>
            </div>
          </template>
          
          <el-row :gutter="12">
            <el-col 
              v-for="product in products" 
              :key="product.id" 
              :xs="24" 
              :sm="12" 
              :md="8" 
              :lg="6"
              class="product-col"
            >
              <el-card :body-style="{ padding: '0px' }" class="product-card">
                <img :src="product.url" class="product-image">
                <div class="product-info">
                  <h3>{{ product.name }}</h3>
                  <div class="product-points">
                    <el-icon><Trophy /></el-icon>
                    {{ product.points }} 积分
                  </div>
                  <div class="product-stock">
                    库存：{{ product.stock }}
                  </div>
                  <el-button
                    type="primary"
                    :disabled="userPoints < product.points || product.stock <= 0"
                    @click="handleExchange(product)"
                  >
                    兑换
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="兑换记录" name="history">
        <el-card class="history-card">
          <template #header>
            <div class="card-header">
              <span>兑换历史</span>
            </div>
          </template>
          <div class="exchange-history-list">
            <el-card
              v-for="record in orderHistory"
              :key="record.id"
              class="exchange-record-card"
              shadow="hover"
            >
              <div class="record-header">
                <span class="product-name">{{ record.productName }}</span>
                <el-tag :type="record.status === 'success' ? 'success' : 'info'" size="small">
                  {{ record.status === 'success' ? '成功' : '处理中' }}
                </el-tag>
              </div>
              <div class="record-info">
                <div class="info-item">
                  <el-icon><Timer /></el-icon>
                  <span>时间: {{ record.createdTime }}</span>
                </div>
                <div class="info-item points-cost">
                  <el-icon><Trophy /></el-icon>
                  <span>消耗 {{ record.pointsUsed }} 积分</span>
                </div>
              </div>
            </el-card>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 兑换确认对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="确认兑换"
      :width="isMobile ? '90%' : '400px'"
      class="exchange-dialog"
    >
      <div class="exchange-confirm">
        <p class="confirm-title">确定要兑换以下商品吗？</p>
        <div class="product-preview">
          <img v-if="selectedProduct?.image" :src="selectedProduct.image" class="preview-image">
          <div class="preview-info">
            <h4>{{ selectedProduct?.name }}</h4>
            <p class="points-info">
              <el-icon><Trophy /></el-icon>
              <span>{{ selectedProduct?.points }} 积分</span>
            </p>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            @click="dialogVisible = false"
            class="cancel-btn"
            :size="isMobile ? 'large' : 'default'"
          >取消</el-button>
          <el-button
            type="primary"
            :loading="exchangeLoading"
            @click="confirmExchange(selectedProduct.id)"
            class="confirm-btn"
            :size="isMobile ? 'large' : 'default'"
          >
            确定兑换
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue'
import { Trophy, Timer, Wallet } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { shopData } from '@/mock/data'
import { useWindowSize } from '@vueuse/core'
import {useApi} from "@/api/product";
import {useUserApi} from "@/api/user"

const activeTab = ref('shop')
const userPoints = ref(0)
const products = ref([])
const dialogVisible = ref(false)
const selectedProduct = ref(null)
const exchangeLoading = ref(false)
const orderHistory = ref([])

const fetchUserPoints = async () => {
  try {
    const response = await useUserApi.getUserPoints()
    userPoints.value = response.data
  } catch (error) {
    ElMessage.error('获取积分信息失败')
  }
}

const fetchProducts = async () => {
  try {
    const res = await useApi.getAllByUser();
    products.value = res.data.records
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  }
}

const fetchOrderHistory = async () => {
  try {
    const res = await useApi.getExchangeRecord();
    if (res.code === 200) {
      orderHistory.value = res.data.records
      return
    }
    ElMessage.error('获取兑换记录失败')
  } catch (error) {
    ElMessage.error('获取兑换记录失败')
  }
}

const handleExchange = (product) => {
  selectedProduct.value = product
  dialogVisible.value = true
}

const confirmExchange = async (id) => {
  if (!selectedProduct.value) return

  exchangeLoading.value = true
  try {
    const res = await useApi.addExchangeRecord(id);
    if (res.code === 200) {
      ElMessage.success('兑换成功')
      await fetchUserPoints()
      await fetchProducts()
      await fetchOrderHistory()
    } else {
      ElMessage.error('兑换失败')
    }
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '兑换失败')
  } finally {
    exchangeLoading.value = false
  }
}

const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

const { width } = useWindowSize()
const isMobile = computed(() => width.value < 768)

onMounted(async () => {
    await fetchUserPoints()
    await fetchProducts()
    await fetchOrderHistory()
})
</script>

<style scoped>
.shop-container {
  padding: 24px;
  max-width: 1280px;
  margin: 0 auto;
}

.points-card {
  margin-bottom: 24px;
  border-radius: 16px;
  background: linear-gradient(135deg, #10B981 0%, #34D399 100%);
  color: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: none;
}

.points-card :deep(.el-card__header) {
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding: 20px;
}

.points-content {
  text-align: center;
  padding: 24px;
}

.points-number {
  font-size: 48px;
  font-weight: bold;
  margin-bottom: 8px;
  background: linear-gradient(135deg, #E0E7FF 0%, #FFFFFF 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.points-label {
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
}

.products-card {
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.product-col {
  margin-bottom: 24px;
}

.product-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  transition: transform 0.2s, box-shadow 0.2s;
  overflow: hidden;
}

.product-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.product-info {
  padding: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.product-info h3 {
  margin: 0 0 12px;
  font-size: 16px;
  font-weight: 600;
  color: #1E293B;
}

.product-points {
  color: #059669;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

.product-stock {
  color: #64748B;
  margin-bottom: 16px;
  font-size: 14px;
}

.product-info .el-button {
  margin-top: auto;
  background: linear-gradient(135deg, #10B981 0%, #34D399 100%);
  border: none;
  border-radius: 8px;
  padding: 12px;
  font-weight: 500;
  transition: opacity 0.2s;
}

.product-info .el-button:hover {
  opacity: 0.9;
}

.product-info .el-button:disabled {
  background: #E2E8F0;
  opacity: 1;
}

.exchange-confirm {
  text-align: center;
  padding: 20px 0;
}

.confirm-title {
  font-size: 18px;
  font-weight: 600;
  color: #1E293B;
  margin-bottom: 20px;
}

.product-preview {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #F8FAFC;
  border-radius: 12px;
}

.preview-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
}

.preview-info {
  flex: 1;
  text-align: left;
}

.preview-info h4 {
  margin: 0 0 8px;
  font-size: 16px;
  color: #1E293B;
}

.points-info {
  color: #059669;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 6px;
}

.dialog-footer {
  display: flex;
  gap: 12px;
}

.dialog-footer .el-button {
  flex: 1;
  margin: 0;
}

.confirm-btn {
  background: linear-gradient(135deg, #10B981 0%, #34D399 100%);
  border: none;
}

@media screen and (max-width: 768px) {
  .exchange-dialog :deep(.el-dialog__body) {
    padding: 20px;
  }

  .product-preview {
    flex-direction: column;
    text-align: center;
  }

  .preview-image {
    width: 120px;
    height: 120px;
  }

  .preview-info {
    text-align: center;
  }

  .points-info {
    justify-content: center;
  }

  .dialog-footer {
    flex-direction: column;
  }

  .dialog-footer .el-button {
    margin: 0;
    height: 44px;
  }
}

.history-card {
  margin-top: 24px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.exchange-history-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 8px;
}

.exchange-record-card {
  border-radius: 12px;
  transition: transform 0.2s;
}

.exchange-record-card:hover {
  transform: translateY(-2px);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.product-name {
  font-size: 16px;
  font-weight: 600;
  color: #1E293B;
}

.record-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #64748B;
  font-size: 14px;
}

.info-item .el-icon {
  font-size: 16px;
}

.points-cost {
  color: #059669;
}

.remaining-points {
  color: #0EA5E9;
}

@media screen and (max-width: 768px) {
  .shop-container {
    padding: 12px;
  }
  
  .points-content {
    padding: 16px;
  }
  
  .points-number {
    font-size: 32px;
  }

  .history-card :deep(.el-table) {
    font-size: 14px;
  }

  .history-card :deep(.el-table__header) {
    display: none;
  }

  .history-card :deep(.el-table__row) {
    display: flex;
    flex-direction: column;
    padding: 12px;
    border-bottom: 1px solid #eee;
  }

  .history-card :deep(.el-table__cell) {
    display: flex;
    padding: 4px 0;
    border: none;
  }

  .history-card :deep(.el-table__cell)::before {
    content: attr(data-label);
    font-weight: bold;
    margin-right: 8px;
    min-width: 80px;
  }
}
</style>